package com.jxust.vhremployee9092.security.config;

import cn.hutool.crypto.SecureUtil;
import com.jxust.debate.pojo.Employee;
import com.jxust.debate.util.CommonResult;
import com.jxust.vhremployee9092.service.TestService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

/**
 * 用户认证、权限
 */
@Component
@Slf4j
public class SelfUserDetailsService implements UserDetailsService {

    @Resource
    private TestService testService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //构建用户信息的逻辑(取数据库/LDAP等用户信息)

        SelfUserDetails userInfo = new SelfUserDetails();
        userInfo.setUsername(username);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        Employee employee = new Employee();
        employee.setUsername(username);
        CommonResult<Employee> employeeByUsername = testService.getEmployeeByUsername(employee);
        if (employeeByUsername.getData() == null){
            throw new UsernameNotFoundException("用户名密码不正确，请重新登陆！");
        }
        Employee data = (Employee) employeeByUsername.getData();
        userInfo.setPassword(SecureUtil.md5(data.getPassword()));// 模拟从数据库中获取的密码原为 123
//        userInfo.setPassword(encoder.encode("123"));// 模拟从数据库中获取的密码原为 123

        log.info("数据库中的密码为{}",SecureUtil.md5(data.getPassword()));
        log.info("设置到userInfo中的密码为{}",userInfo.getPassword());
        Set authoritiesSet = new HashSet();
        GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_ADMIN");// 模拟从数据库中获取用户角色
        authoritiesSet.add(authority);
        userInfo.setAuthorities(authoritiesSet);

        return userInfo;//$2a$10$vMspUrttZJSXyttU0qFMZ.vVUVBb2z2E5GmcgHvzjZIoyU1CVWCx2
    }
}